package com.yonyou.cn.mongodbtest.utils;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtil {
	  public static final String ENCODING_ISO_8859_1 = "ISO-8859-1";
	  
	  public static final String ENCODING_UTF_8 = "UTF-8";
	  
	  public static final String ENCODING_GBK = "gbk";
		/**
		 * @功能 根据给定的pattern在sourceStr中查找子字符串并以list返回
		 * @param sourceStr
		 *            原字符串
		 * @param pattern
		 *            正则表达式(字符串匹配规则)
		 * @return 将所有匹配的字串封装到ArrayList返回
		 */
		public static ArrayList getString(String sourceStr, String pattern) {
			String str = sourceStr;
			Pattern p = Pattern.compile(pattern);
			Matcher m = p.matcher(str);
			ArrayList list = new ArrayList();
			while (m.find()) {
				list.add(m.group(1));
			}
			return list;
		}

		/**
		 * @功能 判断字符串数组是否含有指定字符串
		 * @param source 字符串数组
		 * @param target 待匹配字符串
		 * @return boolean 存在返回true 不存在返回false
		 */
		public static boolean isContain(String source[], String target) {
			return isContain(source,target,false);
		}
		
		/**
		 * @功能 判断字符串数组是否含有指定字符串
		 * @param source 字符串数组
		 * @param target 待匹配字符串
		 * @param ignoreCase 忽略大小写
		 * @return boolean 存在返回true 不存在返回false
		 */
		public static boolean isContain(String source[], String target,boolean ignoreCase) {
		  for (Object obj : source) {
		    if(ignoreCase&&target.equalsIgnoreCase(obj.toString())){//忽略大小写
	        return true;
	      }else if (target.equals(obj.toString())){//不忽略大小写
	        return true;
	      }
		  }
		  return false;
		}

	  /**
	   * @功能 判断字符串数组是否含有指定字符串
	   * @param source 字符串数组
	   * @param target 待匹配字符串
	   * @return boolean 存在返回true 不存在返回false
	   */
	  public static boolean isContain(List list, String target) {
	    return isContain(list,target,false);
		}
	  
	  /**
	   * @功能 判断字符串数组是否含有指定字符串
	   * @param source 字符串数组
	   * @param target 待匹配字符串
	   * @param ignoreCase 忽略大小写
	   * @return boolean 存在返回true 不存在返回false
	   */
	  public static boolean isContain(List list, String target,boolean ignoreCase) {
	    for (int i = 0, listSize = list.size(); i < listSize; i++) {
	      if (list.get(i) instanceof Map || list.get(i) instanceof HashMap) {// 若list内元素为map则遍历map
	        Map map = ((Map) list.get(i));
	        for (Object obj : map.values()) {
	          if(ignoreCase&&target.equalsIgnoreCase(obj.toString())){//忽略大小写
	            return true;
	          }else if (target.equals(obj.toString())){//不忽略大小写
	            return true;
	          }
	        }
	      } else {
	        if(ignoreCase&&target.equalsIgnoreCase((String)list.get(i))){//忽略大小写
	          return true;
	        }else if (target.equals(list.get(i))){//不忽略大小写
	          return true;
	        }
	      }
	    }
	    return false;
	  }

		/**
		 * @功能 判断字符串数组是否含有指定字符串
		 * @param source 字符串数组
		 * @param target 待匹配字符串
		 * @return boolean 存在返回true 不存在返回false
		 */
		public static boolean isContain(Map source, String target) {
			return isContain(source,target,false);
		}
		
		/**
	   * @功能 判断字符串数组是否含有指定字符串
	   * @param source 字符串数组
	   * @param target 待匹配字符串
	   * @param ignoreCase 忽略大小写
	   * @return boolean 存在返回true 不存在返回false
	   */
	  public static boolean isContain(Map source, String target,boolean ignoreCase) {
	    for (Object obj: source.values()) {
	      if(ignoreCase&&target.equalsIgnoreCase(obj.toString())){//忽略大小写
	        return true;
	      }else if (target.equals(obj.toString())){//不忽略大小写
	        return true;
	      }
	    }
	    return false;
	  }

		/**
		 * 判断是否为空
		 * 
		 * @param target
		 * @return
		 * @author
		 */
		public static boolean isNull(Object target) {
			int len = 0;
	    if (null == target) {
	      return true;
	    }else if (target instanceof CharSequence){
	    	if(((CharSequence) target).length() == 0)return true;
	    	if(target == ""||"null".equals(target)||"undefined".equals(target))return true;
	      return false;
	    }else if (target instanceof Collection){
	      return ((Collection) target).isEmpty();
	    }else if (target instanceof Map){
	      return ((Map) target).isEmpty();
	    }else if (target instanceof Object[]) {
	      Object[] object = (Object[]) target;
	      if (object.length == 0) {
	        return true;
	      }
	     /* boolean empty = true;//数组不做深度校验，只检查一维
	      for (int i = 0; i < object.length; i++) {
	        if (!isNull(object[i])) {
	          empty = false;
	          break;
	        }
	      }
	      return empty;*/
	    }
			return false;
		}
		/**
		 * 将给定的list转化为sql语句中的in条件
		 * 
		 * @param list
		 * @return
		 * @author
		 */
		public static String createInCondition(List list) {
			if(isNull(list)||list.size()==0){
				return "('')";
			}
			StringBuffer inConditon = new StringBuffer();
			inConditon.append("(");
			for (int i = 0, listSize = list.size(); i < listSize; i++) {
				if (list.get(i) instanceof Map || list.get(i) instanceof HashMap) {
					Map map = ((Map) list.get(i));
					for (Object obj : map.values()) {
						inConditon.append("'" + obj.toString() + "',");
					}
				} else {
					inConditon.append("'" + list.get(i) + "',");
				}
			}
			inConditon.append(")");
			return inConditon.replace(inConditon.length() - 2, inConditon.length() - 1, "").toString();
		}

		/**
		 * 将给定的map转化为sql语句中的in条件
		 * 
		 * @param map
		 * @return
		 * @author
		 */
		public static String createInCondition(Map map) {
			if(isNull(map)||map.isEmpty()){
				return "('')";
			}
			StringBuffer inConditon = new StringBuffer();
			inConditon.append("(");
			for (Object object : map.values()) {
				inConditon.append("'" + object.toString() + "',");
			}
			inConditon.append(")");
			return inConditon.replace(inConditon.length() - 2, inConditon.length() - 1, "").toString();
		}

		/**
		 * 将给定的String[]转化为sql语句中的in条件
		 * 
		 * @param str
		 * @return
		 * @author
		 */
		public static String createInCondition(String[] str) {
			if(isNull(str)||str.length==0){
				return "('')";
			}
			StringBuffer inConditon = new StringBuffer();
			inConditon.append("(");
			for (String tar : str) {
				inConditon.append("'" + tar + "',");
			}
			inConditon.append(")");
			return inConditon.replace(inConditon.length() - 2, inConditon.length() - 1, "").toString();
		}
		/**
		 * 在已有的in条件中插入新值
		 * @param inCondition 原有in条件
		 * @param target 待插入值
		 * @return  
		 * @author
		 */
		public static String insertIntoInCondition(String inCondition, String target) {
			StringBuffer tar = new StringBuffer(inCondition);
			int len = tar.length();
			tar.insert(tar.length() - 1, ",'" + target + "'");
			if (len == 0) {
				tar.replace(0, 1, "");
				tar.insert(0, "(");
				tar.insert(tar.length() - 1, ")");
			}
			return tar.toString();
		}
		/**
		 * 在已有的in条件中插入新值
		 * @param inCondition 原有in条件
		 * @param target 待插入值
		 * @return  
		 * @author
		 */
		public static String insertIntoInCondition(StringBuffer inCondition, String target) {
			int len = inCondition.length();
			inCondition.insert(inCondition.length() - 1, ",'" + target + "'");
			if (len == 0) {
				inCondition.replace(0, 1, "");
				inCondition.insert(0, "(");
				inCondition.insert(inCondition.length() - 1, ")");
			}
			return inCondition.toString();
		}
		public static String[] paramListToStringArr(List list){
			int len = list.size();
			String param[] = new String[len];
			for (int i = 0; i < len; i++) {
				param[i] = list.get(i).toString();
			}
			return param;
		}
		/**
		 * 创建 like or 条件
		 * @param list
		 * @param target
		 * @return  
		 * @author
		 */
	  public static String createLikeOrCondtion(List list, String target) {
	    if (isNull(list) || list.size() == 0) {
	      return " ";
	    }
	    StringBuffer condition = new StringBuffer();
	    condition.append("(");
	    for (int i = 0, listSize = list.size(); i < listSize; i++) {
	      if (list.get(i) instanceof Map || list.get(i) instanceof HashMap) {
	        Map map = ((Map) list.get(i));
	        for (Object obj : map.values()) {
	          condition.append("'" + obj.toString() + "' like " + target + " or ");
	        }
	      } else {
	        condition.append("'" + list.get(i) + "' like " + target + " or ");
	      }
	    }
	    String res = condition.toString().trim();
	    res = res.substring(0,res.length()-2)+")";
	    return res;
	  }
	  
	  /**
	   * 创建 like or 条件
	   * @param list
	   * @param target
	   * @return  
	   * @author
	   */
	  public static String createLikeOrCondtion(List list, String target,String pre) {
	    if (isNull(list) || list.size() == 0) {
	      return " ";
	    }
	    StringBuffer condition = new StringBuffer();
	    condition.append("(");
	    for (int i = 0, listSize = list.size(); i < listSize; i++) {
	      if (list.get(i) instanceof Map || list.get(i) instanceof HashMap) {
	        Map map = ((Map) list.get(i));
	        for (Object obj : map.values()) {
	          if(StringUtil.isNull(pre)||target.equals("normal")){
	            condition.append("'" + obj.toString() + "' like " + target + " or ");
	          }else{
	            condition.append(target + " like " + "'" + obj.toString() + "%' or ");
	          }
	        }
	      } else {
	        if(StringUtil.isNull(pre)||target.equals("normal")){
	          condition.append("'" + list.get(i) + "' like " + target + " or ");
	        }else{
	          condition.append(target + " like '" + list.get(i) + "%' " + " or ");
	        }
	      }
	    }
	    String res = condition.toString().trim();
	    res = res.substring(0,res.length()-2)+")";
	    return res;
	  }
	  
	  /**
	   * 判断字符串是否空
	   * */
	  public static boolean isEmpty(Object o){
	    if (o==null || o.toString().length()==0){
	      return true;
	    }
	    return false;
	  }
	  
	  public static SimpleDateFormat SIM_DATEFMT = new SimpleDateFormat("yyyy-MM-dd");//小写的mm表示的是分钟
	 

	  /**
	   * 根据日期字符串生成日期类型
	   * */
	  public static Date string2Date(String dateStr) {
	    if (isEmpty(dateStr)) {
	      return null;
	    }
	    Date date = null;
	    try {
	      date = SIM_DATEFMT.parse(dateStr);
	    } catch (ParseException e) {
	      e.printStackTrace();
	    }
	    return date;
	  }
	  
	  public static List strArrToList(Object[] src){
	    return strArrToList(src,null); 
	  }
	  
	  /**
	   * 
	   * @功能 数组转List<Map>
	   * @param src 数组
	   * @param fieldName map中key值
	   * @return List
	   */
	  public static List strArrToList(Object[] src,String fieldName){
	    List resList = new ArrayList();
	    if(!isNull(src)){
	      for (int i = 0,len = src.length; i < len; i++) {
	        if (isNull(fieldName)) {
	          resList.add(src[i]);
	        }else{
	          Map map = new HashMap();
	          map.put(fieldName, src[i]);
	          resList.add(map);
	        }
	      }
	    }
	    return resList;
	  }
	  /**
	   * 
	   * @功能 将AS_VAL表查的结果放入Map中(非此用途禁用)
	   * @param list
	   * @return
	   */
	  public static Map ListToMap(List list){
	    Map map = ListToMap(list,"VAL_ID","VAL");
	    return map;
	  }
	  /**
	   * 
	   * @功能 将Map中指定键值对 作为key和val
	   * @param list
	   * @param idKey 作为新Map的key的 key
	   * @param valKey作为新Map的val的 key
	   * @return
	   */
	  public static Map ListToMap(List list,String idKey,String valKey){
	    Map map = new HashMap();
	    for (int i = 0,listSize = list.size(); i < listSize; i++) {
	      Map tempMap = (Map) list.get(i);
	      if(!isNull(tempMap)){
	        map.put(tempMap.get(idKey), tempMap.get(valKey));
	      }
	    }
	    return map;
	  }
	  /**
	   * 
	   * @功能 将list转为map
	   * @param list
	   * @param field
	   * @return
	   */
	  public static Map ListToMap(List list,String field){
	    Map map = new HashMap();
	    for (int i = 0,listSize = list.size(); i < listSize; i++) {
	      Map tempMap = (Map) list.get(i);
	      Object object = tempMap.get(0);
	      if(!isNull(object)){
	        map.put(field, object);
	      }
	    }
	    return map;
	  }
	  /**
	   * 
	   * @功能 数组转List
	   * @param obj
	   * @return
	   */
	  public static List arrayToList(Object obj[]){
	    List list = null;
	    if(!isNull(obj)){
	      list = new ArrayList(Arrays.asList(obj));
	    }else{
	      list = new ArrayList();
	    }
	    return list;
	  }
	  /**
	   * 
	   * @功能 将被括号包裹的形如"[001]北京"的字符串拆分成数组
	   * @param str
	   * @param separator 右侧的回括号
	   * @return
	   */
	  public static String[] splitToArr(String str,String separator){
	    String res[] = str.split(separator);
	    if(res.length > 0){
	      String firstStr = res[0];
	      res[0] = firstStr.substring(1);
	    }
	    return res;
	  }
	  /**
	   * @功能 过滤字符串中的所有空格
	   * @param str
	   * @return
	   */
	  public static String trim(String str){
	    if (!StringUtil.isNull(str)) {
	      return str.trim().replace(" ", "");
	    }else{
	      return "";
	    }
	  }
	  /**
	   * @功能 数组转Map
	   * @param src
	   * @return
	   */
	  public static Map strArrToMap(Object[] src){
	    Map map = new HashMap();
	    for (int i = 0,len = src.length; i < len; i++) {
	      map.put(i, src[i]);
	    }
	    return map;
	  }
	  /**
	   * 
	   * @作者 lizhq2
	   * @创建时间 2016-9-20
	   * @功能 过滤空串
	   * @param obj
	   * @return 若为空则返回 空字符串否则返回原字符串
	   */
	  public static String nvl(String obj){
	    if(isNull(obj)){
	      return "";
	    }else{
	      return obj;
	    }
	  }
	  /**
	   * 
	   * @作者 lizhq2
	   * @创建时间 2016-9-21
	   * @功能 list转String
	   * @param list
	   * @return String
	   */
	  public static String listToStr(List list){
	    return listToStr(list,"","");
	  }
	  /**
	   * 
	   * @作者 lizhq2
	   * @创建时间 2016-9-21
	   * @功能 将list转换成字符串按分隔符分隔
	   * @param list
	   * @param sep
	   * @return String
	   */
	  public static String listToStr(List list,String sep){
	    return listToStr(list,"",sep);
	  }
	  /**
	   * 
	   * @作者 lizhq2
	   * @创建时间 2016-9-21
	   * @功能 将list转换成字符串按分隔符分隔
	   * @param list
	   * @param sep
	   * @return String
	   */
	  public static String listToStr(List list,String field,String sep){
	    return listToStr(list,(Object)field,sep);
	  }
	  /**
	   * 
	   * @作者 lizhq2
	   * @创建时间 2016-9-21
	   * @功能 将list转换成字符串按分隔符分隔，如果list内容是Map则取key为field的值，如果field为空则取map第一个值
	   * @param list
	   * @param field
	   * @param sep
	   * @return
	   */
	  public static String listToStr(List list,Map fieldMap,String sep){
	    return listToStr(list,(Object)fieldMap,sep);
	  }
	  /**
	   * 
	   * @作者 lizhq2
	   * @创建时间 2016-9-21
	   * @功能 将list转换成字符串按分隔符分隔，如果list内容是Map则取key为field的值，如果field为空则取map第一个值
	   * @param list
	   * @param field
	   * @param sep
	   * @return
	   */
	  public static String listToStr(List list,List fieldList,String sep){
	    return listToStr(list,(Object)fieldList,sep);
	  }
	  /**
	   * 
	   * @作者 lizhq2
	   * @创建时间 2016-9-21
	   * @功能 将list转换成字符串按分隔符分隔，如果list内容是Map则取key为field的值，如果field为空则取map第一个值
	   * @param list
	   * @param field
	   * @param sep
	   * @return
	   */
	  public static String listToStr(List list,String field[],String sep){
	    return listToStr(list,(Object)field,sep);
	  }
	  /**
	   * 
	   * @作者 lizhq2
	   * @创建时间 2016-9-21
	   * @功能 将list转换成字符串按分隔符分隔，如果list内容是Map则取key为field的值，如果field为空则取map第一个值
	   * @param list
	   * @param field
	   * @param sep
	   * @return
	   */
	  private static String listToStr(List list,Object field,String sep){
	    StringBuffer stringBuffer = new StringBuffer();
	    if (null == list)return "";
	    if(isNull(sep))sep = ",";
	    for(int index = 0,size=list.size();index < size;index++){
	      Object obj = list.get(index);
	      if(obj instanceof Map){
	        Map tempMap = (Map)obj;
	        if(isNull(tempMap))continue;//map为空跳过本次循环
	        if(field instanceof Map){//key 包含多个值以Map形式
	          for (Object value : ((Map)field).values()) {
	            stringBuffer.append(sep).append(tempMap.get(value));
	          }
	        }else if(field instanceof List){//key 包含多个值以List形式
	          for (Object value : (List)field) {
	            stringBuffer.append(sep).append(tempMap.get(value));
	          }
	        }else if(field instanceof String[]){//key 包含多个值以String[]形式
	          for (Object value : (String[])field) {
	            stringBuffer.append(sep).append(tempMap.get(value));
	          }
	        }else if(field instanceof CharSequence){
	          stringBuffer.append(sep).append(tempMap.get(field));
	        }       
	      }else if(obj instanceof CharSequence){
	        stringBuffer.append(sep).append(obj.toString());
	      }
	    }
	    String res = stringBuffer.toString();
	    res = isNull(res)?"":res.substring(1);
	    return res;
	  }
	  
	  public static List getFieldListFromRowList(List rowList,String field){
	    List resList = new ArrayList();
	    for (int index = 0,size = rowList.size(); index < size; index++) {
	      Map row = (Map) rowList.get(index);
	      Object obj = row.get(field);
	      if(!resList.contains(obj)){//不计入重复的
	        resList.add(obj);
	      }
	    }
	    return resList;
	  }
	  public static final String[] REGEX_SPEC_CHARS = { "\\", "$", "(", ")", "*", "+", ".", "[", "]", "?", "^", "{", "}", "|" };

	  /**
	   * 是否包含正则表达式特殊字符
	   * */
	  public static boolean hasRegexSpecifiedChar(String s){
	    if(s==null || s.length()==0){
	      return false;
	    }
	    for (int idx = 0, len = REGEX_SPEC_CHARS.length; idx < len; idx++) {
	      return s.contains(REGEX_SPEC_CHARS[idx]);
	    }
	    return false;
	  }
	  
	  /**
	   * 正则表达式特殊字符转移
	   * */
	  public static String transRegex(String s){
	    String newstr = new String(s);
	    for (int idx = 0, len = REGEX_SPEC_CHARS.length; idx < len; idx++) {
	      if (newstr.contains(REGEX_SPEC_CHARS[idx])) {
	        newstr = newstr.replace(REGEX_SPEC_CHARS[idx], "\\" + REGEX_SPEC_CHARS[idx]);
	      }
	    }
	    return newstr;
	  }
	  
	  public static String getCodeName(String code,String name){
	    StringBuffer res = new StringBuffer();
	    if(!isNull(name)){
	      res.append("[");
	      res.append(code);
	      res.append("]");
	      res.append(name);
	    }else if(!isNull(code)){
	      res.append(code);
	    }
	    return res.toString();
	  }
	  public static String objToStr(Object obj){
	    String res = "";
	    if(isNull(obj)){
	      return res;
	    }else if(obj instanceof BigDecimal){
	      res = ((BigDecimal)obj).toString();
	    }else if(obj instanceof CharSequence){
	      res = (String)obj;
	    }else {
	      res = obj.toString();
	    }
	    return res;
	  }
	  public static Object getOneField(List list,String fieldName){
	    return getOneField(list, 0, fieldName);
	  }
	  
	  public static Object getOneField(List list,int index,String fieldName){
	    Object obj = null;
	    if(!isNull(list)){
	      Map map = (Map) list.get(index);
	      obj = map.get(fieldName);
	    }
	    return obj;
	  }
	  
	  /**
	   * 
	   * @作者 lizhq2
	   * @创建时间 2016-12-12
	   * @功能 取list子集
	   * @param title
	   * @param content
	   * @param limitContent 有效子集
	   * @param limitField 有效子集对应的字段
	   * @param tarField
	   * @return
	   */
	  public static List getSubList(List content, List limitContent, String limitField) {
	    if (!StringUtil.isNull(limitContent)) {
	      if (content.get(0) instanceof Map) {
	        for (int index = 0, size = content.size(); index < size; index++) {
	          Map curMap = (Map) content.get(index);
	          Object limitValue = curMap.get(limitField);
	          if (!limitContent.contains(limitValue)) {
	            content.remove(index);
	          }
	        }
	      } else {
	        for (int index = 0, size = content.size(); index < size; index++) {
	          Object tarValue = content.get(index);
	          if (!limitContent.contains(tarValue)) {
	            content.remove(index);
	          }
	        }
	      }
	    }
	    return content;
	  }
	  /**
	   * 
	   * @作者 lizhq2
	   * @创建时间 2017-1-16
	   * @功能 删除字符串中的特殊字符如：\t \r \n
	   * @param str
	   * @return
	   */
	  public static String replaceSpe(String str) {
	    String dest = "";
	    if (str!=null) {
	      Pattern p = Pattern.compile("\\t|\r|\n");
	      Matcher m = p.matcher(str);
	      dest = m.replaceAll("");
	    }
	    return dest;
	  }

	  public static String getMethodName(String pfix,String field){
	  	return pfix+field.substring(0,1).toUpperCase()+field.substring(1);
	  }
	  
	  public static void main(String[] args) {
	    List resList = new ArrayList();
	    resList.add(11);
	    resList.add(22);
	    System.out.println(createLikeOrCondtion(resList,"ins_type_code","pre"));
	  }
}
